package com.game.caro.server;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.apache.mina.core.service.IoHandler;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.game.caro.data.PlayRoom;
import com.game.caro.data.PlayTable;
import com.game.caro.data.Player;

public class CaroProtocolHandler implements IoHandler 
{
	private static final Logger logger=LoggerFactory.getLogger(CaroProtocolHandler.class);
	
	
	public void exceptionCaught(IoSession session, Throwable cause)throws Exception 
	{		
		logger.warn("Unexpected exception:"+cause);
	}

	/**
	 *  
	 * Xu ly yeu cau tu client gui len
	 * Client gui len co format: command| chuoi thong tin...<--ok
	 */
	public void messageReceived(IoSession session, Object message) throws Exception 
	{
		//message la LOGIN|VAN|1<- client gui len luc dau, ah cai nay la do mina no tu dong tach cho minh theo dong giong nhu trong socket co readline ay, vi the khi viet clietn gui len server minh phai them \n vao cuoi moi chuoi gui len
		//vay lam sao ma nhan duoc chuoi JOINROOM|ROOMNAME <- sau do client gui chuoi nay
		Player player = (Player)session.getAttribute("player");
		String msg = (String)message;
		player.messageReceived(msg);
		
	}

	public void messageSent(IoSession session, Object message) throws Exception 
	{
		
		
	}

	public void sessionClosed(IoSession session) throws Exception
	{
		// Xoa sesson khoi mang Server.ioSessions, e viet di, chi v ben nay cham lam
		if(session!=null)
		{
			// TODO  Gui thong tin session closed ve cho client
			
			// 1.Xoa thong tin trong du lieu
			// a.xoa trong Server.ioSessions
			Server.ioSessions.remove(session.getId());
					
	
			Player player = (Player)session.getAttribute("player");
			
			PlayTable playTable = player.getCurrentPlayTable(); 
			playTable.removePlayer(player);
			
			// TEST
			logger.debug("Session closed: " + session.getId() + ", numbers of session:" +  Server.ioSessions.size());
		
		}
	}

	public void sessionCreated(IoSession session) throws Exception 
	{	
		
	}

	public void sessionIdle(IoSession session, IdleStatus status) throws Exception 
	{	
		
	}

	public void sessionOpened(IoSession session) throws Exception 
	{	
		// Khoi tao player, gan cho ioSession do
		Player player = new Player(session);
		session.setAttribute("player", player);
 
		
		
		// Luu iosession tao ra vao mang Server.ioSessions
		Server.ioSessions.put(session.getId(), session);
		
		// TEST
		logger.debug("Session opened: " + session.getId() + ", numbers of session:" +  Server.ioSessions.size());
	}
	//gio viet ham tra ve ban choi hien hanh?
	
	
	
}
